import {Component, OnInit, ViewChild, AfterViewInit} from "@angular/core";
import {Router, ActivatedRoute} from "@angular/router";
import {Theme} from "./theme";
import {ThemesService} from "./themes.service";
import {MsgResult} from "../../../models/msg-result";
import {Path} from "../../../portal/admin/admin-breadcrumb/breadcrumb";
import {PageSubject} from "../../../util/page-subject";
import {OneDialogService} from "../../../widgets/one-dialog/one-dialog.service";
import {OneOperationComponent} from "../../../widgets/one-operation/one-operation.component";
import {API, MsgConstants} from "../../../constants/constants";
import {ResponseUtil} from "../../../util/response-util";
import {TableUtil} from "../../../util/table-util";

declare var $;

@Component({
  selector: 'app-themes',
  templateUrl: './themes.component.html'
})
export class ThemesComponent implements OnInit,AfterViewInit {
  @ViewChild(OneOperationComponent) operation: OneOperationComponent;
  //接收初始化
  themes: Theme[];
  message: string;
  id: string;
  theme: Theme;
  table;

  constructor(private router: Router,
              private route: ActivatedRoute,
              private dialogService: OneDialogService,
              private themesService: ThemesService,
              private response: ResponseUtil,
              private tableUtil:TableUtil,
              private pageSubject: PageSubject) {
  }

  proxy = {
    "themeAdd": () => this.themeAdd(),
    "themeUpdate": () => this.themeUpdate(),
    "themeDelete": () => this.themeDelete()
  }

  ngOnInit() {
    this.pushPage();
    this.loadThemes();
  }

  ngAfterViewInit() {
    //操作函数代理
    this.operation.proxy = this.proxy;
  }

  /**
   *  生成面包屑
   */
  private pushPage() {
    let path = new Path("权限系统", null);
    this.pageSubject.pushPage("主题管理", "查询", path);
  }

  search() {
    this.table.bootstrapTable('refresh');
  }

  /**
   * 主题查询
   */
  loadThemes() {
    this.table = this.tableUtil.load("one_table_theme",{
      columns: [
        {checkbox: true },
        {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
        {field: "name", title: '名称', align: 'left'},
        {field: "code", title: '编码', align: 'left'},
        {field: "isEnable", title: '启用', align: 'left', formatter: this.yesOrNoFormat},
        {field: "isDefault", title: '默认', align: 'left', formatter: this.yesOrNoFormat},
        {field: "creatorName", title: '创建人', align: 'left', visible: false},
        {field: "create_date", title: '创建日期', align: 'left', sortName: "create_date", sortable: true, visible: false},
        {field: "editorName", title: '修改人', align: 'left', visible: false},
        {field: "modified_date", title: '修改日期', align: 'left', sortName: "modified_date", sortable: true, order:'asc', visible: false}
      ],
      idField: "id",
      sidePagination: 'server',
      pagination: true,
      pageNumber: 1,
      pageSize: 15,
      pageList: [10,15, 50],
      paginationPreText: "上一页",
      paginationNextText: "下一页",
      paginationLoop: false,//是否开启循环分页
      singleSelect: true,//单选
      clickToSelect: true,//点击选中
      toolbar: "#one_operation_themes",
      url: API.themePageListV2,
      method: 'post',
      //传递附加参数
      queryParams: (params) => {
        params.name = $("#themeName").val();
        params.code = $("#themeCode").val();
        return params;
      },
      //返回数据处理器
      responseHandler: (result) => {
        return this.response.bsPageHandler(result, (result) => {
          result.data.rows.forEach(function (value) {
            value.create_date = value.createDate || '';
            value.modified_date = value.modifiedDate || '';
          });
        });
      },
      // //返回数据处理器
      // responseHandler:(result)=>{
      //   //将返回结果映射处理，防止field和数据库中cloumn不一致不能排序
      //   result.rows.forEach(function (value, index, array) {
      //       value.create_date = value.createDate || '';
      //       value.modified_date = value.modifiedDate || '';
      //   });
      //   return result;
      // },
      height: 700,//table高度
      sortable: true,
      sortOrder: 'asc',
      sortName: 'modified_date',
      // search:true,//是否显示搜索框
      // searchOnEnterKey:true,//点击enter键是否触发搜索事件
      // searchText:'',//默认搜索内容
      // smartDisplay:true,//智能显示分页或card视图
      showColumns: true,//显示自定义显示列按钮
      showRefresh: true,//显示刷新按钮
      minimumCountColumns: 3,//最少保留显示的列数量
      showToggle: true,//显示视图切换按钮
      showPaginationSwitch: true,//显示是否分页切换按钮
      //css
      classes: "table table-hover",
      striped: true,//隔行变色
      mobileResponsive: true//响应式
    });
    this.tableUtil.bindResetTableView(this.table);

    // this.table = $("#one_table_theme").bootstrapTable({
    //   columns: [
    //     {checkbox: true},
    //     {field: "id", title: 'ID', align: 'left', visible: false, switchable: false},
    //     {field: "name", title: '名称', align: 'left'},
    //     {field: "code", title: '编码', align: 'left'},
    //     {field: "isEnable", title: '启用', align: 'left', formatter: this.yesOrNoFormat},
    //     {field: "isDefault", title: '默认', align: 'left', formatter: this.yesOrNoFormat},
    //     {field: "creatorName", title: '创建人', align: 'left'},
    //     {field: "create_date", title: '创建日期', align: 'left', sortName: "CREATE_DATE", sortable: true},
    //     {field: "editorName", title: '修改人', align: 'left', visible: false},
    //     {field: "modified_date", title: '修改日期', align: 'left', sortName: "MODIFIED_DATE", sortable: true, visible: false}
    //   ],
    //   idField: "id",
    //   sidePagination: 'server',
    //   pagination: true,
    //   pageNumber: 1,
    //   pageSize: 15,
    //   pageList: [10,15, 50],
    //   paginationPreText: "上一页",
    //   paginationNextText: "下一页",
    //   paginationLoop: false,//是否开启循环分页
    //   singleSelect: true,//单选
    //   clickToSelect: true,//点击选中
    //   toolbar: "#one_operation_themes",
    //   url: API.themePageListV2,
    //   method: 'post',
    //   ajaxOptions:{
    //     headers: {"Authorization":"Bearer " + this.dataStorage.get(AppConstants.token)}
    //   },
    //   //传递附加参数
    //   queryParams: (params) => {
    //     params.name = $("#themeName").val();
    //     params.code = $("#themeCode").val();
    //     return params;
    //   },
    //   //返回数据处理器
    //   responseHandler: (result) => {
    //     return this.response.bsPageHandler(result, (result) => {
    //       result.data.rows.forEach(function (value) {
    //         value.create_date = value.createDate || '';
    //         value.modified_date = value.modifiedDate || '';
    //       });
    //     });
    //   },
    //   // //返回数据处理器
    //   // responseHandler:(result)=>{
    //   //   //将返回结果映射处理，防止field和数据库中cloumn不一致不能排序
    //   //   result.rows.forEach(function (value, index, array) {
    //   //       value.create_date = value.createDate || '';
    //   //       value.modified_date = value.modifiedDate || '';
    //   //   });
    //   //   return result;
    //   // },
    //   height: 700,//table高度
    //   sortable: true,
    //   order: 'asc',
    //   sortName: 'MODIFIED_DATE',
    //   // search:true,//是否显示搜索框
    //   // searchOnEnterKey:true,//点击enter键是否触发搜索事件
    //   // searchText:'',//默认搜索内容
    //   // smartDisplay:true,//智能显示分页或card视图
    //   showColumns: true,//显示自定义显示列按钮
    //   showRefresh: true,//显示刷新按钮
    //   minimumCountColumns: 3,//最少保留显示的列数量
    //   showToggle: true,//显示视图切换按钮
    //   showPaginationSwitch: true,//显示是否分页切换按钮
    //   //css
    //   classes: "table table-hover",
    //   striped: true,//隔行变色
    //   mobileResponsive: true//响应式
    // });
  }

  //实现添加页面跳转
  themeAdd() {
    this.router.navigate(['add'], {relativeTo: this.route});
  }

  //实现修改页面跳转
  themeUpdate() {
    let rows = this.table.bootstrapTable('getSelections');
    if (rows.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      let id = rows[0].id;
      this.router.navigate(['update', {themeId: id}], {relativeTo: this.route});
    }
  }

  //实现删除弹窗
  themeDelete() {
    let rows = this.table.bootstrapTable('getSelections');
    if (rows.length != 1) {
      this.dialogService.modalInfo("请选择一条数据");
    } else {
      this.id = rows[0].id;
      this.dialogService.modalInfoWithCancelBtn("确定删除？", this.requestDelete);
    }
  }

  //确认删除按钮
  private requestDelete = () => {
    //调用后端接口
    this.themesService.deleteTheme(this.id).subscribe(
      result => this.response.success(result, this.processDeleteResult),
      error => this.response.error(error)
    );
  }

  private processDeleteResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success(result.message);
      this.search();
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * yesOrNo格式化函数
   * @param value
   * @param row
   * @param index
   * @returns {any}
   */
  private yesOrNoFormat(value, row, index) {
    if (value == '1') {
      return "是";
    }
    if (value == '0') {
      return "否"
    }
  }


}

